package cn.wolfcode.luowowo2.website.web.controller;

import cn.wolfcode.luowowo2.cache.prefix.UserInfoKeyPrefix;
import cn.wolfcode.luowowo2.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo2.common.util.AssertUtil;
import cn.wolfcode.luowowo2.common.util.DisableExeption;
import cn.wolfcode.luowowo2.member.domain.UserInfo;
import cn.wolfcode.luowowo2.member.service.IUserInfoService;

import cn.wolfcode.luowowo2.util.AjaxResult;
import cn.wolfcode.luowowo2.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * Created by Albert on 2019/7/5.
 */
@Controller
public class LoginController {
    @Reference
    private IUserInfoService userInfoService;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @RequestMapping("/checkPhone")
    @ResponseBody
    public boolean checkPhone(String phone){
        return !userInfoService.checkPhone(phone);
    }

    @RequestMapping("/userRegist")
    @ResponseBody
    public AjaxResult regist(String phone, String nickname, String password, String rpassword, String verifyCode){
       /* AjaxResult ajaxResult = null;
        try {
            userInfoService.userRegist(phone,nickname,password,rpassword,verifyCode);
            ajaxResult = new AjaxResult();
        }catch (DisableExeption de){
            de.printStackTrace();
            ajaxResult = new AjaxResult();
            ajaxResult.setMsg(de.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            ajaxResult = new AjaxResult("系统错误,请联系管理员");
        }
        return ajaxResult;*/ //在使用了ExceptionAdvice后可以不使用上面的代码

        userInfoService.userRegist(phone,nickname,password,rpassword,verifyCode);
        return new AjaxResult();
    }

    @RequestMapping("/userLogin")
    @ResponseBody
    public Object userLogin(HttpSession session, HttpServletResponse response, String username, String password){
        //在userLogin方法中包含了存入Redis的方法
        String token = userInfoService.userLogin(username,password);
        if (token==null) {
            throw new DisableExeption("账号或密码错误");
        }

        //这里引入response对象是因为cookie需要通过response写在浏览器中,写入的只是token
        CookieUtil.addCookie(response,UserInfoKeyPrefix.USER_INFO_TOKEN_COOKIE_NAME,token);

        //session中的信息需要从redis中获取,拿到的是一个UserInfo对象
        session.setAttribute("userInfo",userInfoRedisService.getUserInfoByToken(UserInfoKeyPrefix.USER_INFO_TOKEN,token));

        return new AjaxResult();
    }

}
